package com.fy.spring.controller;


import com.fy.spring.lb.ILoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RequestMapping(value = "/consumer/payment")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private ILoadBalance loadBalance;
    @Resource
    private DiscoveryClient discoveryClient;


    @GetMapping("/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances =
                discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalance.instance(instances);
        URI uri = serviceInstance.getUri();
        System.out.println(uri + "/payment/lb");
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }
}
